package com.itjin.controller;

import com.itjin.model.domain.vo.BeautifiedContentVO;
import com.itjin.model.result.Result;
import com.itjin.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/upload")
@Tag(name = "通用控制器", description = "文件上传和内容处理")
@Slf4j
public class CommonController {

  @Resource
  private CommonService commonService;

  // 支持的图片类型
  private static final List<String> IMAGE_TYPES = Arrays.asList(
      "image/jpeg", "image/jpg", "image/png", "image/gif", "image/bmp", "image/webp"
  );

  // 支持的文档类型
  private static final List<String> DOCUMENT_TYPES = Arrays.asList(
      "application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation",
      "text/plain", "application/zip", "application/x-rar-compressed"
  );

  // 支持的音频类型
  private static final List<String> AUDIO_TYPES = Arrays.asList(
      "audio/mpeg", "audio/wav", "audio/ogg", "audio/aac", "audio/mp4"
  );

  // 支持的视频类型
  private static final List<String> VIDEO_TYPES = Arrays.asList(
      "video/mp4", "video/avi", "video/mov", "video/wmv", "video/flv", "video/webm"
  );

  @PostMapping("/avatar")
  @Operation(summary = "上传头像")
  public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
    try {
      if (file.isEmpty()) {
        return Result.failure(400, "文件不能为空");
      }
      // 校验文件大小（例如：限制5MB）
      if (file.getSize() > 5 * 1024 * 1024) {
        return Result.failure(400, "文件大小不能超过5MB");
      }
      // 校验文件类型
      String contentType = file.getContentType();
      if (contentType == null || !contentType.startsWith("image/")) {
        return Result.failure(400, "只能上传图片文件");
      }

      // 上传文件并获取访问URL
      String fileUrl = commonService.uploadFile(file);
      return Result.success(fileUrl);
    } catch (Exception e) {
      log.error("文件上传失败", e);
      return Result.failure(500, "文件上传失败: " + e.getMessage());
    }
  }

  /**
   * 通用文件上传接口
   */
  @PostMapping("/file")
  @Operation(summary = "通用文件上传", description = "支持图片、文档、音频、视频等多种文件类型上传到OSS")
  public Result<Map<String, Object>> uploadFile(
      @Parameter(description = "上传的文件") @RequestParam("file") MultipartFile file,
      @Parameter(description = "文件类型(image/document/audio/video/other)") @RequestParam(defaultValue = "other") String fileType,
      @Parameter(description = "自定义文件夹路径") @RequestParam(required = false) String folder) {
    
    try {
      // 基础验证
      if (file.isEmpty()) {
        return Result.failure(400, "文件不能为空");
      }

      String contentType = file.getContentType();
      if (contentType == null) {
        return Result.failure(400, "无法识别文件类型");
      }

      // 根据文件类型设置不同的限制和文件夹
      Result<String> validationResult = validateFileByType(file, fileType, contentType);
      if (validationResult.getCode() != 200) {
        return Result.failure(validationResult.getCode(), validationResult.getMessage());
      }

      // 确定上传文件夹
      String uploadFolder = determineUploadFolder(fileType, folder);

      // 上传文件
      String fileUrl = commonService.uploadFileGeneral(file, uploadFolder);

      // 构建返回信息
      Map<String, Object> result = Map.of(
          "url", fileUrl,
          "originalName", file.getOriginalFilename(),
          "size", file.getSize(),
          "contentType", contentType,
          "folder", uploadFolder
      );

      log.info("通用文件上传成功: {} -> {}", file.getOriginalFilename(), fileUrl);
      return Result.success(result);

    } catch (Exception e) {
      log.error("通用文件上传失败", e);
      return Result.failure(500, "文件上传失败: " + e.getMessage());
    }
  }

  /**
   * AI美化帖子内容
   * 
   * @param requestBody 包含需要美化的内容
   * @return 美化后的内容
   */
  @PostMapping("/beautify")
  @Operation(summary = "AI美化帖子内容")
  public Result<BeautifiedContentVO> beautifyContent(@RequestBody Map<String, String> requestBody) {
    try {
      String content = requestBody.get("content");
      if (content == null || content.trim().isEmpty()) {
        return Result.failure(400, "内容不能为空");
      }

      // 字数限制，避免API调用过大
      if (content.length() > 3000) {
        return Result.failure(400, "内容长度不能超过3000字");
      }

      // 调用AI美化服务
      BeautifiedContentVO beautifiedContent = commonService.beautifyPostContent(content);

      // 如果美化失败，给出适当的提示
      if (!beautifiedContent.getIsBeautified()) {
        return Result.success(beautifiedContent);
      }

      return Result.success(beautifiedContent);
    } catch (Exception e) {
      log.error("美化内容失败", e);
      return Result.failure(500, "美化内容失败: " + e.getMessage());
    }
  }

  /**
   * 获取支持的文件类型列表
   */
  @GetMapping("/supported-types")
  @Operation(summary = "获取支持的文件类型", description = "获取各类型支持的文件格式列表")
  public Result<Map<String, List<String>>> getSupportedTypes() {
    Map<String, List<String>> supportedTypes = Map.of(
        "image", IMAGE_TYPES,
        "document", DOCUMENT_TYPES,
        "audio", AUDIO_TYPES,
        "video", VIDEO_TYPES
    );
    return Result.success(supportedTypes);
  }

  // ==================== 私有方法 ====================

  /**
   * 根据文件类型验证文件
   */
  private Result<String> validateFileByType(MultipartFile file, String fileType, String contentType) {
    long maxSize;
    List<String> allowedTypes;

    switch (fileType.toLowerCase()) {
      case "image":
        maxSize = 10 * 1024 * 1024; // 10MB
        allowedTypes = IMAGE_TYPES;
        break;
      case "document":
        maxSize = 50 * 1024 * 1024; // 50MB
        allowedTypes = DOCUMENT_TYPES;
        break;
      case "audio":
        maxSize = 100 * 1024 * 1024; // 100MB
        allowedTypes = AUDIO_TYPES;
        break;
      case "video":
        maxSize = 500 * 1024 * 1024; // 500MB
        allowedTypes = VIDEO_TYPES;
        break;
      case "other":
        maxSize = 100 * 1024 * 1024; // 100MB
        allowedTypes = null; // 允许所有类型
        break;
      default:
        return Result.failure(400, "不支持的文件类型分类: " + fileType);
    }

    // 检查文件大小
    if (file.getSize() > maxSize) {
      return Result.failure(400, String.format("文件大小不能超过%dMB", maxSize / (1024 * 1024)));
    }

    // 检查文件类型（other类型跳过检查）
    if (allowedTypes != null && !allowedTypes.contains(contentType)) {
      return Result.failure(400, "不支持的" + fileType + "文件类型: " + contentType);
    }

    return Result.success("验证通过");
  }

  /**
   * 确定上传文件夹
   */
  private String determineUploadFolder(String fileType, String customFolder) {
    if (customFolder != null && !customFolder.trim().isEmpty()) {
      return customFolder.trim();
    }

    switch (fileType.toLowerCase()) {
      case "image":
        return "images";
      case "document":
        return "documents";
      case "audio":
        return "audios";
      case "video":
        return "videos";
      default:
        return "files";
    }
  }
}
